/**
 * jsonp: 前端传一个自定义方法 调后端接口时调用前端自定义的方法
 *
 * */

const http = require("http")
const https = require("https")
const url = require("url");

const EventEmitter = require("events")

// 设置初始值，防止多次调用垃圾不回收
let event = null

http.createServer((req, res) => {
  const urlObj = url.parse(req.url, true)
  res.writeHead(200, {
    "Content-Type": "application/json;charset=utf-8",
    // cors 头
    "access-control-allow-origin": "*"
  })
  switch (urlObj.pathname) {
    case "/api/aaa":
     // 客户端去 猫眼要数据
      event = new EventEmitter()
      event.on("play", (data) => {
        console.log(1111)
        res.end(data)
      })
      httpget()
      break;
    default:
      res.end("404")
  }
}).listen(3000)


function httpget() {
  let data = ''
  https.get(`https://i.maoyan.com/api/mmdb/movie/v3/list/hot.json?
ct=%E5%8C%97%E4%BA%AC&ci=1&channelId=4`,
    (res) =>  {
      res.on("data", (chunk)=> {
        data+= chunk
      })
      res.on("end", ()=> {
        event.emit("play", data)
      })
    })
}